//
//  UIViewController+Navigation.m
//  MobileCRM
//
//  Created by winter on 16/3/14.
//  Copyright © 2016年 江苏金恒信息科技有限公司. All rights reserved.
//

#import "UIViewController+Navigation.h"
#import <objc/runtime.h>

@implementation UIViewController (Navigation)
+ (void)load
{
    static dispatch_once_t once_t;
    dispatch_once(&once_t, ^{
        Class cs = [self class];
        SEL originSelector = @selector(viewWillAppear:);
        SEL newSelector = @selector(xx_viewWillAppear:);
        Method originMethod = class_getInstanceMethod(cs, originSelector);
        Method newMethod = class_getInstanceMethod(cs, newSelector);
        
        BOOL didAddMethod = class_addMethod(cs, originSelector, method_getImplementation(newMethod), method_getTypeEncoding(newMethod));
        if(didAddMethod)
        {
            class_replaceMethod(cs, newSelector, method_getImplementation(originMethod), method_getTypeEncoding(originMethod));
        }
        else
        {
            method_exchangeImplementations(originMethod, newMethod);
        }
    });
}
- (void)xx_viewWillAppear:(BOOL)animated
{
    [self xx_viewWillAppear:animated];
    if(self.navigationController!=nil && self.navigationItem.backBarButtonItem == nil  && self.navigationController.viewControllers.count>1)
    {
        self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"toolbarBack" inBundle:[NSBundle bundleForClass:self.class] compatibleWithTraitCollection:nil] style:UIBarButtonItemStylePlain target:self action:@selector(navigationBack:)];
    }

}
- (void)navigationBack:(UIBarButtonItem *)sender
{
    if(self.navigationController)
        [self.navigationController popViewControllerAnimated:YES];
}
@end
